﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sale.Models;
using System.IO;

namespace sale.Controllers
{
    public class ImageController : Controller
    {
        //
        // GET: /Image/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFiles(string Name,HttpPostedFileBase image)
        {

            try
            {
                string path = Server.MapPath("~/Images");
                if (image != null)
                {
                    image.SaveAs(Path.Combine(path, image.FileName));
                }
                Image item = new Image()
                {
                    Images = "/Images/" + image.FileName,
                    Name = Name
                };
                if (item.Insert()>0)
                {
                    return PartialView("image_row", item);
                }
                else
                {
                    ModelState.AddModelError("sdfs", "thêm ảnh không thành công");
                }
                return Content(string.Format("name:{0}", Name));
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("error", ex.Message);
            }
            string messages = string.Join("; ", ModelState.Values
                                        .SelectMany(x => x.Errors)
                                        .Select(x => x.ErrorMessage));
            return Json(new { error = messages });
        }
        public ActionResult GetAll()
        {
            return PartialView(Image.ConvertAll(Image.GetAll()));
        }
        public ActionResult Insert()
        {
            //try
            //{
               var item = Request["name"];
            //    string path = Server.MapPath("~/ImageProduct");

            //    if (file != null)
            //        file.SaveAs(path + file.FileName);

            //    return RedirectToAction("Index");
            //}
            //catch (System.Exception ex)
            //{
            //    ModelState.AddModelError("fsfds", ex.Message);
            //}
            //string messages = string.Join("; ", ModelState.Values
            //                            .SelectMany(x => x.Errors)
            //                            .Select(x => x.ErrorMessage));
            //return Json(new { error = messages });
            return RedirectToAction("Index");
        }

    }
}
